package register

import (
	"encoding/json"
	"errors"
	"fmt"
	"ghw2/server/config"
	"net"
)

func RegisterServiceToNameServer() (*net.Conn, error) {
	conn, err := net.Dial("tcp", config.ServerConfig.Namesrv)

	if err != nil {
		fmt.Println(err)
		return nil, err
	}

	_, err = conn.Write([]byte("server"))

	if err != nil {
		conn.Close()
		fmt.Println(err)
		return nil, err
	}

	var n int
	res := make([]byte, 1024)
	n, err = conn.Read(res)

	if err != nil {
		conn.Close()
		fmt.Println(err)
		return nil, err
	}

	// namesrv返回”ok“表示连接无误
	if string(res[:n]) != "ok" {
		conn.Close()
		fmt.Println("连接有误！")
		return nil, errors.New("连接有误！")
	}

	_, err = conn.Write([]byte(config.ServerConfig.Server))

	if err != nil {
		conn.Close()
		fmt.Println(err)
		return nil, err
	}

	// namesrv返回”ok“表示连接无误
	if string(res[:n]) != "ok" {
		conn.Close()
		fmt.Println("连接有误！")
		return nil, errors.New("连接有误！")
	}

	data, _ := json.Marshal(config.ServerConfig.Services)
	_, err = conn.Write(data)

	if err != nil {
		conn.Close()
		return nil, err
	}

	return &conn, nil
}
